package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yuanfeng.commoms.config.ALiPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.dto.GoodsDTO;
import com.yuanfeng.payment.feign.UsermsServiceClient;
import com.yuanfeng.payment.mapper.PayConfigMapper;
import com.yuanfeng.payment.mapper.PayConsumeRecordMapper;
import com.yuanfeng.payment.mapper.PayConsumeTradeBackMapper;
import com.yuanfeng.payment.service.PayStrategyHandleService;
import com.yuanfeng.payment.vo.CallBackVO;
import com.yuanfeng.payment.vo.RecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 支付宝PC支付
 *
 * @author Stranger
 * @date 2023/4/27 9:35
 */
@Service
public class AliPayAPPServiceImpl implements PayStrategyHandleService {


    private static PayConfigMapper payConfigMapper;


    private static PayConsumeTradeBackMapper payConsumeTradeBackMapper;


    private static PayConsumeRecordMapper payConsumeRecordMapper;


    private static UsermsServiceClient usermsServiceClient;


    // 注入的时候，给类的 service 注入
    @Autowired
    public void setMapper(PayConfigMapper payConfigMapper, PayConsumeTradeBackMapper payConsumeTradeBackMapper, PayConsumeRecordMapper payConsumeRecordMapper) {
        AliPayAPPServiceImpl.payConfigMapper = payConfigMapper;
        AliPayAPPServiceImpl.payConsumeRecordMapper = payConsumeRecordMapper;
        AliPayAPPServiceImpl.payConsumeTradeBackMapper = payConsumeTradeBackMapper;

    }

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setUsermsServiceClient(UsermsServiceClient usermsServiceClient) {

        AliPayAPPServiceImpl.usermsServiceClient = usermsServiceClient;
    }

    /**
     * 初始化 阿里云支付参数
     */
    public void initAliPayConfig() {
        //从redis中查询
        String payStr = RedisUtil.get(YFConfig.ALI_PAY_CONFIG);
        Map<String, Object> aliPayConfig;
        if (StringUtils.isEmpty(payStr)) {
            aliPayConfig = payConfigMapper.selectPayConfig("03");
        } else {
            aliPayConfig = JSON.parseObject(payStr, Map.class);
            //将支付配置存入Redis
            RedisUtil.set(YFConfig.ALI_PAY_CONFIG, JSON.toJSON(aliPayConfig).toString());
        }
        if (null != aliPayConfig) {
            ALiPayConfig.URL = aliPayConfig.get("gatewayURL").toString();
            ALiPayConfig.APPID = aliPayConfig.get("appID").toString();
            ALiPayConfig.sellerId = aliPayConfig.get("appMCHId").toString();
            ALiPayConfig.RSA_PRIVATE_KEY = aliPayConfig.get("appAPIKey").toString();
            ALiPayConfig.CERT_PATH = aliPayConfig.get("cert_public_key_res2").toString();
            ALiPayConfig.ROOT_CERT_PATH = aliPayConfig.get("cert_root_key").toString();
            ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH = aliPayConfig.get("cert_app_public_key").toString();
            ALiPayConfig.shopping_notify_url = aliPayConfig.get("shoppingNotifyUrl").toString();
            ALiPayConfig.shopping_notify_url_h5 = aliPayConfig.get("rechargeNotifyUrl2").toString();
            ALiPayConfig.shopping_return_url_pc = aliPayConfig.get("shoppingReturnUrlPc").toString();
        }

    }

    @Override
    public ResponseResult userPayEntrance(Map<Object, Object> para, HttpServletRequest request, HttpServletResponse response) {
        //获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(para.get("token").toString());
        if (null != userInfo) {
            //加载支付配置
            initAliPayConfig();
            //订单号
            String orderId = (String) para.get("orderId");
            //用户id
            String userId = userInfo.getUserId();
            //订单支付金额
            BigDecimal totalPrice = new BigDecimal(0);
            //商品名称
            String goodsName = null;
            //积分订单支付金额
            Integer amountAotalIntegral = null;
            //积分商品 0  是  1 否
            Integer integralGoods = CommonType.goodsType.GOODS_TYPE_ORDINARY.getCode();
            //判断当前订单号是否是 支付单号 或 是订单号
            if (MathUtil.isInteger(orderId)) {
                GoodsDTO queryGoodsPara = payConsumeTradeBackMapper.queryGoodsPriceAndName(orderId, userId);
                totalPrice = queryGoodsPara.getTradePaymentAmount();
                goodsName = queryGoodsPara.getTradeDesc();
                //获取积分商品订单的积分
                Integer totalIntegral = queryGoodsPara.getTotalIntegral();
                //积分商品 0  是  1 否
                integralGoods = queryGoodsPara.getIntegralGoods();
                amountAotalIntegral = totalIntegral;
            } else {
                RecordVO rp = payConsumeRecordMapper.queryRecordPara(orderId);
                totalPrice = rp.getRecordMoney();
                goodsName = rp.getRecordDesc();

                // 获取积分商品的积分
                String totalIntegral = RedisUtil
                        .get(YFConfig.YF_USERINTEGRALYPAID + "--" + para.get("token") + "--" + userId);
                if (null != totalIntegral) {
                    //amountAotalIntegral 不为null 证明是积分订单
                    amountAotalIntegral = Integer.valueOf(totalIntegral);
                    //积分商品 0  是  1 否
                    integralGoods = CommonType.goodsType.GOODS_TYPE_INTEGRAL.getCode();
                }
            }
            //如果是积分商品判断 当前用户积分是否支持购买
            if (null != integralGoods && integralGoods == 0) {
                //获取用户积分
                Integer userIntegral = usermsServiceClient.getMemberIntegralByUserId(userId);
                if (null != userIntegral && amountAotalIntegral > userIntegral) {
                    return ResponseResult.fail(BizCodeEnume.PAY_INTEGRAL_ERROR.getCode(), BizCodeEnume.PAY_INTEGRAL_ERROR.getMsg());
                }
            }
            try {
                //查询 封装支付参数
                List<CallBackVO> callBackParaList = new ArrayList<CallBackVO>();
                callBackParaList = treasureOrder(userInfo, orderId);
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                // 支付宝网关
                certAlipayRequest.setServerUrl(ALiPayConfig.URL);
                // 应用id
                certAlipayRequest.setAppId(ALiPayConfig.APPID);
                // 应用私钥路径
                certAlipayRequest.setPrivateKey(ALiPayConfig.RSA_PRIVATE_KEY);
                // 应用公钥路径
                certAlipayRequest.setCertPath(ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH);
                // 支付宝应用公钥证书路径
                certAlipayRequest.setAlipayPublicCertPath(ALiPayConfig.CERT_PATH);
                // 支付宝证书，根证书路径
                certAlipayRequest.setRootCertPath(ALiPayConfig.ROOT_CERT_PATH);
                //设置签名
                certAlipayRequest.setSignType(ALiPayConfig.SIGNTYPE);
                // 设置签名类型
                certAlipayRequest.setFormat(ALiPayConfig.FORMAT);
                // 设置编码
                certAlipayRequest.setCharset(ALiPayConfig.CHARSET);

                AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);


                // 设置请求参数
                AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

                // 商户订单号，商户网站订单系统中唯一订单号，必填
                String out_trade_no = orderId;
                // 付款金额，必填
                String total_amount = String.valueOf(totalPrice);
                // 订单名称，必填
                String subject = goodsName;
                // 商品描述，可空
                String body = "购物";
                // 封装请求支付信息
                AlipayTradePagePayModel model = new AlipayTradePagePayModel();
                model.setPassbackParams(JsonUtils.toString(callBackParaList));
                model.setOutTradeNo(out_trade_no);
                model.setTotalAmount(total_amount);
                model.setSubject(subject);
                model.setBody(body);
                model.setTimeoutExpress("30m");
                // 销售产品码 必填
                model.setProductCode("FAST_INSTANT_TRADE_PAY");
                alipayRequest.setBizModel(model);
                alipayRequest.setReturnUrl(ALiPayConfig.shopping_notify_url_h5);
                alipayRequest.setNotifyUrl(ALiPayConfig.shopping_notify_url);
                // 调用SDK生成表单
                String result = alipayClient.pageExecute(alipayRequest).getBody();
                response.setContentType("text/html;charset=" + ALiPayConfig.CHARSET);

                return ResponseResult.success(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL.getCode(), BizCodeEnume.TOKEN_IS_ILLEGAL.getMsg());
    }

    private List<CallBackVO> treasureOrder(UserInfoVO userInfo, String orderId) {
        List<CallBackVO> callBackParaList = null;
        try {
            String userId = userInfo.getUserId();
            String userName = userInfo.getUserName();

            callBackParaList = new ArrayList<CallBackVO>();
            CallBackVO callBackPara = new CallBackVO();
            callBackPara.setUserId(userId);
            callBackPara.setUserName(userName);
            String treasureShopId = null;

            if (MathUtil.isInteger(orderId)) {
                GoodsDTO queryGoodsPara = payConsumeTradeBackMapper.queryGoodsPriceAndName(orderId, userId);
                BigDecimal paymentAmount = queryGoodsPara.getTradePaymentAmount();
                treasureShopId = payConsumeTradeBackMapper.queryTreasureShopIdByInt(orderId);
                //订单金额
                callBackPara.setOrderFullAmount(paymentAmount.toString());
                //店铺id
                callBackPara.setShopId(treasureShopId);
                callBackParaList.add(callBackPara);
            } else {

                List<RecordVO> rp = payConsumeRecordMapper.queryRecordParaList(orderId);
                for (int i = 0; i < rp.size(); i++) {
                    callBackPara = new CallBackVO();
                    //买家用户名
                    callBackPara.setUserName(userName);
                    //买家用户id
                    callBackPara.setUserId(userId);
                    String[] str = rp.get(i).getRecordPayorder().split(",");

                    List<String> shopIdList = Arrays.asList(str);

                    for (int j = 0; j < shopIdList.size(); j++) {
                        //店铺id
                        treasureShopId = payConsumeTradeBackMapper.queryTreasureShopIdByInt(shopIdList.get(j));
                        callBackPara.setShopId(treasureShopId);
                    }
                    callBackPara.setOrderFullAmount(rp.get(i).getRecordMoney().toString());
                    callBackParaList.add(callBackPara);
                }
            }

        } catch (Exception e) {
        }
        return callBackParaList;
    }


}
